package com.nl.strings;

public class ReverseString {

	//翻转单词
	public static void reverseWorld(char[] str) {
		//翻转整个字符串
		reverse(str, 0, str.length-1);
		//翻转每个单词
		int start = 0,end=0;
		while(end<str.length){
			while(end<str.length&& str[start]==' '){
				start++;
				end++;
			}
			while(end <str.length && str[end]!=' '){
				end++;
			}
			reverse(str, start, end-1);

			//移动指针
			if(end<str.length&&str[end]==' '){
				start=end;
			}
		}
	}
	
	//左旋字符串
	public static void leftRotate(char[]str,int n){
		n=n%str.length;
		if(str==null || n<1){
			throw new RuntimeException("parameter invalid");
		}
		//旋转整个字符串
		reverse(str, 0, str.length-1);
		reverse(str, 0, str.length-n-1);
		reverse(str,  str.length-n,str.length-1);
	}
	
	public static void reverse(char[] str,int start,int end){
		if(str==null || start>end||end>=str.length){
			throw new RuntimeException("parameter invalid");
		}
		while(start<end){
			char t=str[start];
			str[start] = str[end];
			str[end] = t;
			start++;
			end--;
		}
	}
	
	public static void main(String[] args) {
		char[] arr = "I am a students.".toCharArray();
		reverseWorld(arr);
		System.out.println(new String(arr));

		char[] arr1 = "abcdefg".toCharArray();
		leftRotate(arr1,2);
		System.out.println(new String(arr1));
	}
}
